package com.hxzy.consumer;

import com.hxzy.common.RabbitMQConst;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者（手动消费模型）
 */
@Component
@Log4j2
public class MailQueueConsumer {


    /**
     * 必须在application.yml中配置
     *     # 开启手动消费模式
     * spring:
     *   rabbitmq:
     *     listener:
     *       simple:
     *         acknowledge-mode: manual
     * 线程1
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConst.MAIL_QUEUE})
    @RabbitHandler
    public void  receiver(Message message, Channel channel) throws IOException {

        MessageProperties messageProperties = message.getMessageProperties();

        String uuid= messageProperties.getHeader("spring_returned_message_correlation");

        // 从redis的已经消息的列表中查询 uuid是否存在 多个消费者才会有这个问题
        if(true){
            //向rabbitmq服务器发送消息处理成功的标识
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  // 手动确认消息
            return;
        }




        long id=message.getMessageProperties().getDeliveryTag();

        log.info(id);
        log.info(messageProperties);

        byte[] body = message.getBody();

        String msg=new String(body);

        try{
            System.out.println(Thread.currentThread().getId()+",收到消息："+msg);
            //做处理的逻辑，
            //向rabbitmq服务器发送消息处理成功的标识
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);  // 手动确认消息


        }catch(Exception e){
            log.error(e);

            //向rabbitmq服务器发送消失败的标识, 重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);
        }
    }

}
